import 'package:fishing/models/booking_args.dart';
import 'package:fishing/models/pond_seat.dart';
import 'package:fishing/services/home_service.dart';
import 'package:fishing/providers/user_provider.dart';
import 'package:fishing/widgets/message_overlay.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';

class FishingBooklPage extends StatefulWidget {
  final String id;
  final BookingArgs? bookingArgs;
  const FishingBooklPage({
    super.key,
    required this.id,
    this.bookingArgs,
  });

  @override
  State<FishingBooklPage> createState() => _FishingBooklPageState();
}

class _FishingBooklPageState extends State<FishingBooklPage> {
  final HomeService _homeService = HomeService();
  // 定义颜色
  final Color primaryBlue = const Color(0xFF2196F3);
  final Color availableColor = const Color(0xFF4CAF50);
  final Color occupiedColor = const Color(0xFFE53935);

  // 选中的钓位
  String? selectedSpot;
  PondSeat? selectedSeat;

  List<PondSeat> _spots = [];
  
  // 日期时间相关
  DateTime selectedDate = DateTime.now(); // 默认当天
  
  // 时间段列表
  List<Map<String, dynamic>> timeSegments = [];
  
  // 当前正在添加的时间段
  TimeOfDay? currentStartTime;
  
  // 预约状态
  bool _isBooking = false;

  @override
  void initState() {
    super.initState();
    _loadSeats();
  }

  Future<void> _loadSeats() async {
    final List<PondSeat> seats = await _homeService.getPondSeatList(
      deptId: int.parse(widget.bookingArgs?.deptId ?? '0'),
      priceSegmentId:
          int.parse(widget.bookingArgs?.priceSegmentId as String),
    );
    setState(() {
      _spots = seats;
    });
  }

  // 选择日期
  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(const Duration(days: 30)),
    );
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
        // 清空已选择的时间段，因为日期变了
        timeSegments.clear();
        currentStartTime = null;
      });
    }
  }

  // 获取结束时间（根据开始时间和钓鱼时长计算）
  TimeOfDay? _calculateEndTime(TimeOfDay startTime) {
    if (widget.bookingArgs?.durationHours == null) {
      return null;
    }
    
    final startMinutes = startTime.hour * 60 + startTime.minute;
    final endMinutes = startMinutes + (widget.bookingArgs!.durationHours * 60);
    
    // 处理跨天情况（如果结束时间超过24小时，取模）
    final endHour = (endMinutes ~/ 60) % 24;
    final endMinute = endMinutes % 60;
    
    return TimeOfDay(hour: endHour, minute: endMinute);
  }

  // 选择开始时间
  Future<void> _selectStartTime() async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: currentStartTime ?? _getMinimumStartTime(),
    );
    if (picked != null) {
      // 验证选择的时间是否符合要求
      if (!_isValidStartTime(picked)) {
        final minTime = _getMinimumStartTime();
        MessageOverlay.show(
          context, 
          message: '预约时间必须在当前时间的30分钟之后（最早${minTime.hour.toString().padLeft(2, '0')}:${minTime.minute.toString().padLeft(2, '0')}）',
          type: MessageType.warning
        );
        return;
      }
      
      setState(() {
        currentStartTime = picked;
      });
    }
  }

  // 获取最小可预约时间（当前时间+30分钟）
  TimeOfDay _getMinimumStartTime() {
    final now = DateTime.now();
    
    // 如果选择的是今天，需要加30分钟
    if (DateFormat('yyyy-MM-dd').format(selectedDate) == DateFormat('yyyy-MM-dd').format(now)) {
      final minDateTime = now.add(const Duration(minutes: 30));
      // 将分钟数向上取整到5分钟的倍数，便于用户选择
      final roundedMinute = ((minDateTime.minute / 5).ceil() * 5) % 60;
      final adjustedHour = minDateTime.hour + (minDateTime.minute + 4) ~/ 60; // 如果分钟进位则小时+1
      
      return TimeOfDay(
        hour: adjustedHour % 24, 
        minute: roundedMinute
      );
    } else {
      // 如果选择的是未来日期，可以从00:00开始
      return const TimeOfDay(hour: 0, minute: 0);
    }
  }

  // 验证开始时间是否有效
  bool _isValidStartTime(TimeOfDay startTime) {
    final now = DateTime.now();
    
    // 如果选择的不是今天，则时间有效
    if (DateFormat('yyyy-MM-dd').format(selectedDate) != DateFormat('yyyy-MM-dd').format(now)) {
      return true;
    }
    
    // 如果是今天，需要检查时间是否在当前时间30分钟之后
    final selectedDateTime = DateTime(
      selectedDate.year,
      selectedDate.month,
      selectedDate.day,
      startTime.hour,
      startTime.minute,
    );
    
    // 获取最小时间用于比较
    final minTime = _getMinimumStartTime();
    final minDateTime = DateTime(
      selectedDate.year,
      selectedDate.month,
      selectedDate.day,
      minTime.hour,
      minTime.minute,
    );
    
    // 允许选择等于或大于最小时间的时间
    return selectedDateTime.isAfter(minDateTime) || selectedDateTime.isAtSameMomentAs(minDateTime);
  }

  // 添加时间段
  void _addTimeSegment() {
    if (currentStartTime == null || selectedSeat == null) {
      return;
    }

    // 再次验证时间（防止用户修改日期后时间变得无效）
    if (!_isValidStartTime(currentStartTime!)) {
      final minTime = _getMinimumStartTime();
      MessageOverlay.show(
        context, 
        message: '预约时间必须在当前时间的30分钟之后（最早${minTime.hour.toString().padLeft(2, '0')}:${minTime.minute.toString().padLeft(2, '0')}）',
        type: MessageType.warning
      );
      return;
    }

    final endTime = _calculateEndTime(currentStartTime!);
    if (endTime == null) {
      return;
    }

    // 检查同一钓位的时间冲突
    final newStartMinutes = currentStartTime!.hour * 60 + currentStartTime!.minute;
    final newEndMinutes = endTime.hour * 60 + endTime.minute;

    for (var segment in timeSegments) {
      // 只检查同一钓位的时间冲突
      if (segment['seatId'] == selectedSeat!.id) {
        final existingStartMinutes = segment['startTime'].hour * 60 + segment['startTime'].minute;
        final existingEndMinutes = segment['endTime'].hour * 60 + segment['endTime'].minute;
        
        // 检查时间重叠
        if ((newStartMinutes < existingEndMinutes && newEndMinutes > existingStartMinutes)) {
          final seatCode = selectedSeat!.code;
          MessageOverlay.show(context, message: '钓位$seatCode在该时间段已有预约，请选择其他时间', type: MessageType.warning);
          return;
        }
      }
    }

    setState(() {
      timeSegments.add({
        'seatId': selectedSeat!.id,
        'appointmentDate': DateFormat('yyyy-MM-dd').format(selectedDate),
        'startTime': currentStartTime!,
        'endTime': endTime,
      });
      currentStartTime = null; // 清空当前选择
    });
  }

  // 删除时间段
  void _removeTimeSegment(int index) {
    setState(() {
      timeSegments.removeAt(index);
    });
  }


  // 格式化时间段为后端需要的格式
  List<Map<String, dynamic>> _formatTimeSegmentsForApi() {
    return timeSegments.map((segment) {
      return {
        'seatId': segment['seatId'],
        'appointmentDate': segment['appointmentDate'],
        'startTime': '${segment['startTime'].hour.toString().padLeft(2, '0')}:${segment['startTime'].minute.toString().padLeft(2, '0')}',
        'endTime': '${segment['endTime'].hour.toString().padLeft(2, '0')}:${segment['endTime'].minute.toString().padLeft(2, '0')}',
      };
    }).toList();
  }

  // 确认预约
  Future<void> _confirmBooking() async {
    if (selectedSeat == null) {
      MessageOverlay.show(context, message: '请选择钓位');
      return;
    }
    
    if (timeSegments.isEmpty) {
      MessageOverlay.show(context, message: '请至少添加一个时间段');
      return;
    }

    final userProvider = Provider.of<UserProvider>(context, listen: false);
    if (userProvider.user == null) {
      MessageOverlay.show(context, message: '请先登录');
      return;
    }

    setState(() {
      _isBooking = true;
    });

    try {
      final formattedTimeSegments = _formatTimeSegmentsForApi();
      final success = await _homeService.createAppointment(
        deptId: selectedSeat!.deptId,
        pondId: selectedSeat!.pondId,
        userId: userProvider.user!.userId,
        timeSegments: formattedTimeSegments,
      );

      if (success) {
        // 显示预约成功弹窗
        _showBookingSuccessDialog();
      } else {
        MessageOverlay.show(context, message: '预约失败，请稍后重试', type: MessageType.error);
      }
    } catch (e) {
      MessageOverlay.show(context, message: '预约失败：$e', type: MessageType.error);
    } finally {
      if (mounted) {
        setState(() {
          _isBooking = false;
        });
      }
    }
  }

  // 获取按钮文本
  String _getButtonText() {
    if (selectedSpot == null) {
      return '请选择钓位';
    }
    
    if (timeSegments.isEmpty) {
      return '请添加时间段';
    }
    
    return '确认预约 (${timeSegments.length}个时间段)';
  }

  // 获取按钮点击事件
  VoidCallback? _getButtonOnPressed() {
    if (_isBooking) {
      return null; // 预约中时禁用按钮
    }
    
    if (selectedSpot == null) {
      return null; // 未选择钓位时禁用按钮
    }
    
    if (timeSegments.isEmpty) {
      return null; // 未添加时间段时禁用按钮
    }
    
    return _confirmBooking; // 可以预约时返回预约方法
  }

  // 显示预约成功弹窗
  void _showBookingSuccessDialog() {
    showDialog(
      context: context,
      barrierDismissible: false, // 不允许点击外部关闭
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: Column(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.green,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.check,
                  color: Colors.white,
                  size: 30,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                '预约成功！',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.green,
                ),
              ),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '您已成功预约 ${timeSegments.length} 个时间段',
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.grey,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),
              Text(
                '请按时到场享受钓鱼乐趣！',
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
          actions: [
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      Navigator.of(context).pop(); // 关闭弹窗
                      // 继续预约 - 清空当前选择，留在此页面
                      _resetBookingState();
                    },
                    style: OutlinedButton.styleFrom(
                      side: BorderSide(color: primaryBlue),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: Text(
                      '继续预约',
                      style: TextStyle(
                        color: primaryBlue,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      Navigator.of(context).pop(); // 关闭弹窗
                      // 跳转到预约查看页面
                      context.push('/prebook');
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryBlue,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: const Text(
                      '查看预约',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  // 重置预约状态（继续预约时使用）
  void _resetBookingState() {
    setState(() {
      selectedSpot = null;
      selectedSeat = null;
      timeSegments.clear();
      currentStartTime = null;
      selectedDate = DateTime.now(); // 重置为今天
      _isBooking = false;
    });
  }

  // 构建时间段选择器
  Widget _buildTimeSegmentSelector() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '已选择钓位：$selectedSpot',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: primaryBlue,
            ),
          ),
          const SizedBox(height: 15),
          Row(
            children: [
              const Text(
                '预约日期：',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
              InkWell(
                onTap: _selectDate,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: primaryBlue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(color: primaryBlue.withOpacity(0.3)),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        DateFormat('yyyy-MM-dd').format(selectedDate),
                        style: TextStyle(
                          fontSize: 14,
                          color: primaryBlue,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(width: 4),
                      Icon(Icons.calendar_today, size: 16, color: primaryBlue),
                    ],
                  ),
                ),
              ),
              if (DateFormat('yyyy-MM-dd').format(selectedDate) == DateFormat('yyyy-MM-dd').format(DateTime.now()))
                const Text(
                  ' (今天)',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
            ],
          ),
          const SizedBox(height: 15),
          Row(
            children: [
              const Text(
                '添加时间段：',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Spacer(),
              if (DateFormat('yyyy-MM-dd').format(selectedDate) == DateFormat('yyyy-MM-dd').format(DateTime.now()))
                Text(
                  '最早${_getMinimumStartTime().hour.toString().padLeft(2, '0')}:${_getMinimumStartTime().minute.toString().padLeft(2, '0')}',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.orange,
                    fontWeight: FontWeight.w500,
                  ),
                ),
            ],
          ),
          const SizedBox(height: 10),
          
          // 时间段添加区域
          Row(
            children: [
              Expanded(
                child: InkWell(
                  onTap: _selectStartTime,
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey[400]!),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          currentStartTime != null 
                              ? '${currentStartTime!.hour.toString().padLeft(2, '0')}:${currentStartTime!.minute.toString().padLeft(2, '0')}'
                              : '选择开始时间',
                          style: TextStyle(
                            fontSize: 14,
                            color: currentStartTime != null ? Colors.black : Colors.grey[600],
                          ),
                        ),
                        Icon(Icons.access_time, size: 18, color: Colors.grey[600]),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 10),
              ElevatedButton(
                onPressed: currentStartTime != null ? _addTimeSegment : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: primaryBlue,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                ),
                child: const Text(
                  '添加',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ],
          ),
          
          // 显示当前选择的结束时间
          if (currentStartTime != null) ...[
            const SizedBox(height: 8),
            Row(
              children: [
                const Text(
                  '结束时间：',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                Text(
                  _calculateEndTime(currentStartTime!) != null
                      ? '${_calculateEndTime(currentStartTime!)!.hour.toString().padLeft(2, '0')}:${_calculateEndTime(currentStartTime!)!.minute.toString().padLeft(2, '0')}'
                      : '--:--',
                  style: TextStyle(
                    fontSize: 12,
                    color: primaryBlue,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  ' (${widget.bookingArgs?.durationHours ?? 0}小时)',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ],
          
          // 已添加的时间段列表
          if (timeSegments.isNotEmpty) ...[
            const SizedBox(height: 15),
            const Text(
              '已选择的时间段：',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            ...timeSegments.asMap().entries.map((entry) {
              final index = entry.key;
              final segment = entry.value;
              final startTime = segment['startTime'] as TimeOfDay;
              final endTime = segment['endTime'] as TimeOfDay;
              final seatCode = _spots.firstWhere((seat) => seat.id == segment['seatId']).code;
              
              return Container(
                margin: const EdgeInsets.only(bottom: 8),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(color: Colors.blue[200]!),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                decoration: BoxDecoration(
                                  color: primaryBlue,
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: Text(
                                  '钓位$seatCode',
                                  style: const TextStyle(
                                    fontSize: 12,
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '${startTime.hour.toString().padLeft(2, '0')}:${startTime.minute.toString().padLeft(2, '0')} - ${endTime.hour.toString().padLeft(2, '0')}:${endTime.minute.toString().padLeft(2, '0')}',
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '${widget.bookingArgs?.durationHours ?? 0}小时 • ${segment['appointmentDate']}',
                            style: const TextStyle(
                              fontSize: 12,
                              color: Colors.grey,
                            ),
                          ),
                        ],
                      ),
                    ),
                    IconButton(
                      onPressed: () => _removeTimeSegment(index),
                      icon: const Icon(Icons.delete, color: Colors.red, size: 20),
                      constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
                      padding: EdgeInsets.zero,
                    ),
                  ],
                ),
              );
            }).toList(),
          ],
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: true, // 键盘弹出时调整布局
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => context.pop(),
        ),
        title: const Text('钓位预定'),
        centerTitle: true,
        backgroundColor: Colors.blue,
        scrolledUnderElevation: 0,
        elevation: 0,
      ),
      body: Column(
        children: [
          // 钓场信息
          Container(
            padding: const EdgeInsets.all(15),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 钓场名称和价格
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      widget.bookingArgs?.pondName ?? '未知鱼塘',
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '¥${widget.bookingArgs?.price ?? '无价格'}元 / ${widget.bookingArgs?.durationHours ?? '?'}小时',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: primaryBlue,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 15),
                // 营业时间
                Row(
                  children: [
                    const Icon(
                      Icons.access_time,
                      size: 16,
                      color: Colors.grey,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      widget.bookingArgs?.openHours ?? '未知营业时间',
                      style: const TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 15),

                // 钓位基本信息
                const Row(
                  children: [
                    Text(
                      '钓位信息：',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(width: 10),
                    Text(
                      '总钓位 30 个，可用 11 个',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 钓位状态说明
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: Row(
              children: [
                Container(
                  width: 16,
                  height: 16,
                  decoration: BoxDecoration(
                    color: availableColor,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                const SizedBox(width: 8),
                const Text('可选'),
                const SizedBox(width: 20),
                Container(
                  width: 16,
                  height: 16,
                  decoration: BoxDecoration(
                    color: occupiedColor,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                const SizedBox(width: 8),
                const Text('已占'),
              ],
            ),
          ),

          const SizedBox(height: 15),


          // 钓位列表和时间段选择区域
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // 钓位网格
                  Container(
                    height: 300, // 固定高度给钓位网格
                    padding: const EdgeInsets.all(15),
                    child: GridView.builder(
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 5,
                        mainAxisSpacing: 15,
                        crossAxisSpacing: 15,
                        childAspectRatio: 1,
                      ),
                      itemCount: _spots.length,
                      itemBuilder: (context, index) {
                        final spot = _spots[index];
                        final isAvailable = spot.status == 0;
                        final isSelected = selectedSpot == spot.code;

                        return GestureDetector(
                          onTap: isAvailable
                              ? () {
                                  setState(() {
                                    selectedSpot = spot.code;
                                    selectedSeat = spot;
                                  });
                                }
                              : null,
                          child: Container(
                            decoration: BoxDecoration(
                              color: isAvailable
                                  ? (isSelected ? primaryBlue : availableColor)
                                  : occupiedColor,
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: Text(
                                spot.code,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontWeight:
                                      isSelected ? FontWeight.bold : FontWeight.normal,
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  
                  // 时间段选择区域移到这里
                  if (selectedSpot != null) 
                    _buildTimeSegmentSelector(),
                  
                  // 添加额外的底部间距，确保内容不被按钮遮挡
                  SizedBox(height: 80 + MediaQuery.of(context).padding.bottom),
                ],
              ),
            ),
          ),

          // 底部按钮 - 使用SafeArea确保不被底部导航栏遮挡
          SafeArea(
            child: Container(
              padding: const EdgeInsets.all(15),
              margin: const EdgeInsets.only(bottom: 10), // 额外的底部边距
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withAlpha((0.1 * 255).round()),
                    spreadRadius: 1,
                    blurRadius: 6,
                    offset: const Offset(0, -3),
                  ),
                ],
              ),
            child: ElevatedButton(
              onPressed: _getButtonOnPressed(),
              style: ElevatedButton.styleFrom(
                backgroundColor: primaryBlue,
                minimumSize: const Size(double.infinity, 50),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25),
                ),
              ),
              child: _isBooking
                  ? const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        ),
                        SizedBox(width: 10),
                        Text(
                          '预约中...',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    )
                  : Text(
                      _getButtonText(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
            ),
            ),
          ),
        ],
      ),
    );
  }
}
